<template>
  <a-modal
    :visible="visible"
    @cancel="cancelClick"
    :closable="false"
    :width="1100"
    :footer="null"
  >
    <template #title>
      <a-row justify="space-between" align="middle">
        <a-col class="title">一键清理</a-col>
        <a-col>
          <a-space :size="20">
            <div>
              <a-radio-group v-model:value="radioValue" @change="radioChange">
                <a-radio-button value="1">180天前</a-radio-button>
                <a-radio-button value="2">90天前</a-radio-button>
                <a-radio-button value="0_3">按时间</a-radio-button>
                <a-tooltip placement="top">
                  <template #title>
                    <span>按照素材被引用的次数进行筛选</span>
                  </template>
                  <a-radio-button value="0_4">引用次数</a-radio-button>
                </a-tooltip>

              </a-radio-group>
            </div>
            <template v-if="radioValue == '0_3'">   
              <a-range-picker
                v-model:value="dateTime"
                @change="dateTimeChange"
                valueFormat="YYYY/MM/DD"
                :allowClear="false"
              />
            </template>
            <template v-if="radioValue == '0_4'">
              <!-- 用户输入 引用次数 多少 至 多少之间 -->
              <div class="use_number">
                <!-- <span class="use_numbner_title">引用次数：</span> -->
                <a-input-number v-model:value="usage_min" :min="0" :max="100000" @change="numerChangeDebounce"/>
                <span>至</span>
                <a-input-number v-model:value="usage_max" :min="0" :max="100000" @change="numerChangeDebounce"/>
                <span>之间</span>
              </div>
            </template>

            <div style="cursor: pointer" @click="cancelClick">
              <CloseOutlined />
            </div>
          </a-space>
        </a-col>
      </a-row>
    </template>
    <a-spin :spinning="spinning">
      <div class="total-waste">
        <div class="text">共发现可清理垃圾</div>
        <div class="num">{{ totalFileSize }}</div>
      </div>
      <div class="waste-list">
        <a-checkbox-group
          v-model:value="checkboxValue"
          @change="checkboxChange"
          style="width: 100%"
        >
          <a-row :gutter="[16, 16]">
            <a-col :span="24" v-for="item in clearCheckList" :key="item.type">
              <a-checkbox :value="item.type">
                <span class="text">{{ item.title }}</span>
                文件数量{{ item.file_num }}， 占用空间{{
                  item.file_size_format
                }}
              </a-checkbox>
            </a-col>
          </a-row>
        </a-checkbox-group>
      </div>
      <a-row class="footer" justify="space-between" align="middle">
        <a-col>
          已选择
          <span class="text">{{ selectedFile }}</span>
          个文件，共
          <span class="text">{{ totalSize }}</span>
        </a-col>
        <a-col>
          <a-button
            type="primary"
            @click="submitClick"
            style="border-radius: 5px"
            >移至回收站
          </a-button>
        </a-col>
      </a-row>
    </a-spin>
  </a-modal>
</template>

<script>
import {
  reactive,
  toRefs,
  watch,
  defineComponent,
  ref,
  createVNode,
} from "vue";
import {
  CloseOutlined,
  ExclamationCircleOutlined,
} from "@ant-design/icons-vue";
import { message, Modal } from "ant-design-vue";
import dayjs from "dayjs";
import request from "../../../../common/utils/request";

import utils from '@/common/utils/utils'
export default defineComponent({
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
  },
  components: { CloseOutlined },
  setup(props, { emit }) {
    const state = reactive({
      count: 0,
      radioValue: "1",
      dateTime: [dayjs().startOf("day").subtract(30, "day"), dayjs()],
      checkboxValue: [],
      spinning: false,
      clearCheckList: [],
      totalSize: "0B",
      totalFileSize: "",
      selectedFile: 0,

      // 素材引用次数 - 用户随便填, 最终提交的时候, 判断大小
      usage_min:0,
      usage_max:0
    });

    const cancelClick = () => {
      emit("onCancel");
    };

    const dateTimeChange = (date) => {
      state.totalSize = "0B";
      state.selectedFile = 0;
      getClearDetail();
    };

    const radioChange = ({ target }) => {
      if (target.value == 0) {
        state.dateTime = [dayjs().startOf("day").subtract(30, "day"), dayjs()];
      }
      state.totalSize = "0B";
      state.selectedFile = 0;
      getClearDetail();
    };

    const numerChange = (e) => {
      getClearDetail();
    };

    // 防抖
    const numerChangeDebounce = utils.debounce(500, numerChange);
    const checkboxChange = (key) => {
      let sum = 0;
      state.selectedFile = 0;
      if (!key.length) {
        state.clearCheckList.forEach((item) => {
          if (item.file_size) {
            sum += parseInt(item.file_size);
          }
        });
        state.totalSize = "0B";
        getConversion(sum);
        return;
      }
      state.clearCheckList.forEach((item) => {
        key.forEach((e) => {
          if (item.type == e) {
            sum += parseInt(item.file_size);
            state.selectedFile += parseInt(item.file_num);
          }
        });
      });
      getConversion(sum);
    };

    // 计算求和接口
    const getConversion = (size) => {
      request
        .get("/work_ai", "/user/shotstack/size/conversion", { size })
        .then((res) => {
          if (state.checkboxValue.length) {
            state.totalSize = res.result;
          } else {
            state.totalFileSize = res.result;
          }
        });
    };

    const submitClick = () => {
      if (!state.checkboxValue.length) {
        message.warn("请先选择需要清理的文件");
        return;
      }
      Modal.confirm({
        title: "提示",
        icon: "",
        content: "确定移至回收站吗？",
        cancelText: "取消",
        okText: "确定",
        onOk() {
          let params = {
            search_type: (state.radioValue != 1 && state.radioValue != 2) ? 0 : state.radioValue,
            type: state.checkboxValue,
          };
          if (state.radioValue == '0_3') {
            params.start_time = dayjs(state.dateTime[0]).format("YYYY/MM/DD");
            params.end_time = dayjs(state.dateTime[1]).format("YYYY/MM/DD");
          } else if (state.radioValue ==  '0_4') {
            params.usage_min = state.usage_min
            params.usage_max = state.usage_max
          }
          request
            .del("/work_ai", "/user/shotstack/clear", params)
            .then((res) => {
              state.submitLoading = false;
              state.totalSize = "";
              state.totalFileSize = "";
              emit("onSubmit");
            });
        },
      });
    };

    const getClearDetail = () => {
      let params = {
        search_type: (state.radioValue != 1 && state.radioValue != 2) ? 0 : state.radioValue,
      };
      if (state.radioValue == '0_3') {
        params.start_time = dayjs(state.dateTime[0]).format("YYYY/MM/DD");
        params.end_time = dayjs(state.dateTime[1]).format("YYYY/MM/DD");
      } else if (state.radioValue == '0_4') {
        params.usage_min = state.usage_min
        params.usage_max = state.usage_max
      }

      console.log(params,'提交的参数');

      // return
      
      state.spinning = true;
      request
        .get("/work_ai", "/user/shotstack/clear/detail", params)
        .then((res) => {
          console.log(res,'可删除信息');
          
          state.spinning = false;
          state.clearCheckList = res.result;
          state.checkboxValue = [];
          let sum = 0;
          res.result.forEach((item) => {
            if (item.file_size) {
              sum += parseInt(item.file_size);
            }
          });
          getConversion(sum);
        })
        .catch(() => {
          state.spinning = false;
        });
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          getClearDetail();
        } else {
          state.dateTime = [
            dayjs().startOf("day").subtract(30, "day"),
            dayjs(),
          ];
          state.radioValue = "1";
          state.totalSize = "0B";
          state.selectedFile = 0;
        }
      }
    );

    return {
      ...toRefs(state),
      numerChange,
      numerChangeDebounce,
      cancelClick,
      submitClick,
      checkboxChange,
      radioChange,
      dateTimeChange,
    };
  },
});
</script>

<style lang="less" scoped>
.title {
  font-weight: 600;
}

.total-waste {
  width: 100%;
  height: 80px;
  background: #fff6f6;
  border-radius: 16px;
  display: flex;
  align-items: center;
  padding-left: 20px;
  display: flex;
  align-items: center;
  .text {
    font-size: 20px;
    margin-right: 20px;
  }
  .num {
    font-size: 40px;
    font-weight: 600;
    color: #2878FF;
  }
}

.use_number{
  display: flex;
  align-items: center;
  gap: 5px;
  span{
    font-size: 14px;
    color: #333;
  }
  .use_numbner_title{

  }
}

.waste-list {
  margin-top: 20px;
  .text {
    font-weight: 600;
    margin-right: 10px;
  }
}
.footer {
  margin-top: 60px;
  font-size: 16px;
  .text {
    color: #2878FF;
  }
}
</style>
